/**
 * JAVACC DEMO 1.0
 */
package com.apache.uct.controller;

import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.entity.*;
import com.apache.uct.manager.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  用户权限列表Action
 *
 * @author iussoft 创建时间：2016-3-19
 */
@Controller
@RequestMapping("uct/core/")
public class UserActAction {

    @Autowired
    private UserManager userManager;

    @Autowired
    private ProxyManager uctProxyManager;

    @Autowired
    private ActManager actManager;

    @Autowired
    private ActGiveManager actGiveManager;

    @Autowired
    private RoleGiveManager roleGiveManager;

    @Autowired
    private RoleManager roleManager;

    @Autowired
    private OrgManager orgManager;

    @Autowired
    private DeptManager deptManager;

    @Autowired
    private DataRightManager dataRightManager;

    //跳转到用户权限列表
    @RequestMapping("user-right.action")
    public ModelAndView userRight(HttpServletRequest request, String op, String userId) {
        ModelAndView view = new ModelAndView(getPrefix() + "right");
        view.addObject("op", op);
        view.addObject("userId", userId);
        return view;
    }

    //跳转到对应页签列表
    @RequestMapping("user-act-page.action")
    public ModelAndView userRightAct(HttpServletRequest request, String userId) {
        String type = "uct/" + request.getParameter("gotoPage");
        ModelAndView view = new ModelAndView(type);
        view.addObject("userId", userId);
        return view;
    }

    //直接分配操作权限
    @RequestMapping("user-right-act!data.action")
    @ResponseBody
    public Object dataUserRightAct(HttpServletRequest request, String userId) {
        String actId = Validator.getDefaultStr(request.getParameter("id"), "0");
        Act actVo = new Act();
        actVo.setFatherId(actId);
        ParamsVo<Act> vo = new ParamsVo<Act>();
        vo.setObj(actVo);

        this.getSessionUser(request, vo);

        List<Act> actList = actManager.getList(vo);
        ParamsVo<ActGive> agVo = new ParamsVo<ActGive>();
        agVo.setParams("roleId", userId);
        agVo.setParams("giveType", "user");
        agVo.setKey("GiveListByOrgId");
        List<ActGive> giveList = (List<ActGive>) actGiveManager.execute(agVo);
        JSONArray jary = new JSONArray();
        for (int i = 0; i < actList.size(); i++) {
            Act avo = actList.get(i);
            JSONObject jvo = JSONObject.fromObject(avo);
            if (avo.getSubCount() != null && avo.getSubCount() > 0) {
                jvo.put("state", "closed");
            } else {
                jvo.put("state", "opened");
            }
            String hasGive = hasGive(giveList, avo.getActId()) ? "T" : "F";
            jvo.put("hasGive", hasGive);
            jary.add(jvo);
        }
        return jary;
    }

    /**
     * 执行权限值分配
     */
    @RequestMapping("authorize-act.action")
    @ResponseBody
    public ResultMsg orgAct(HttpServletRequest request, String flag, String id, String objId,
            String actGiveType) throws Exception {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        ParamsVo vo = new ParamsVo();
        vo.setParams("flag", flag);
        vo.setParams("actId", id);
        vo.setParams("objId", objId);
        vo.setParams("actGiveType", actGiveType);
        vo.setKey("actGiveExecute");
        String result = String.valueOf(uctProxyManager.doInvoke(vo));
        if (Validator.isNotNull(result)) {
            rmsg = new ResultMsg("F", "授权失败！");
        }
        return rmsg;
    }

    @RequestMapping("user-right-all!data.action")
    @ResponseBody
    public Object dataUserActAll(HttpServletRequest request,
            @RequestParam(value = "page", required = false) String page,
            @RequestParam(value = "rows", required = false) String rows) {
        Map<String, Object> map = new HashMap<String, Object>();
        ParamsVo<Act> vo = new ParamsVo<Act>();
        vo.setKey("userActAll");
        vo.setParams("pageSize", Validator.getDefaultStr(rows, "20"));
        vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
        vo.setParams("userId", request.getParameter("userId"));
        Page actPage = (Page) actManager.execute(vo);
        map.put("total", actPage.getCount());
        map.put("rows", actPage.getPageObjects());
        return map;
    }

    //拥有的角色
    @RequestMapping("user-role!data.action")
    @ResponseBody
    public Object dataUserRole(HttpServletRequest request,
            @RequestParam(value = "page", required = false) String page,
            @RequestParam(value = "rows", required = false) String rows) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Validator.isNotNull(request.getParameter("userId"))) {
            ParamsVo vo = new ParamsVo();
            vo.setKey("userToRole");
            vo.setParams("pageSize", Validator.getDefaultStr(rows, "20"));
            vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
            vo.setParams("userId", request.getParameter("userId"));

            this.getSessionUser(request, vo);
            ParamsVo uvo = new ParamsVo();
            uvo.setInfoId(request.getParameter("userId"));
            User user = (User) userManager.getInfoById(uvo);
            if (Validator.isNotNull(user.getOrgId())) {
                if (!user.getOrgId().equals(String.valueOf(vo.getParams("userOrgId")))) {
                    vo.setParams("userOrgId", user.getOrgId());
                }
            }
            Page actPage = (Page) roleGiveManager.execute(vo);
            map.put("total", actPage.getCount());
            map.put("rows", actPage.getPageObjects());
        }
        return map;
    }

    //分配角色给用户
    @RequestMapping("role-to-user.action")
    @ResponseBody
    public ResultMsg roleToUser(HttpServletRequest request, String flag, String roleId,
            String userId) {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        ParamsVo<RoleGive> vo = new ParamsVo<RoleGive>();
        RoleGive roleGive = new RoleGive();
        roleGive.setRoleId(roleId);
        roleGive.setUserId(userId);
        if ("add".equals(flag)) {
            roleGive.setCreateTime(System.currentTimeMillis());
            ParamsVo pvo = new ParamsVo();
            if (Validator.isNull(request.getParameter("roleEname"))) {
                pvo.setInfoId(roleId);
                Role role = (Role) roleManager.getInfoById(pvo);
                roleGive.setRoleEname(role.getRoleEname());
            } else {
                roleGive.setRoleEname(request.getParameter("roleEname"));
            }
            pvo.setInfoId(userId);
            User user = (User) userManager.getInfoById(pvo);
            if (!Validator.isEmpty(user)) {
                roleGive.setUserEname(user.getUserEname());
            }
            vo.setObj(roleGive);
            roleGiveManager.saveInfo(vo);
        } else {
            vo.setObj(roleGive);
            roleGiveManager.deleteInfo(vo);
        }
        return rmsg;
    }

    //继承自角色的权限
    @RequestMapping("user-right-role!data.action")
    @ResponseBody
    public Object dataUserRightRole(HttpServletRequest request,
            @RequestParam(value = "page", required = false) String page,
            @RequestParam(value = "rows", required = false) String rows) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Validator.isNotNull(request.getParameter("userId"))) {
            ParamsVo vo = new ParamsVo();
            vo.setKey("userActByRoleId");
            vo.setParams("pageSize", Validator.getDefaultStr(rows, "20"));
            vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
            vo.setParams("userId", request.getParameter("userId"));
            Page actPage = (Page) actManager.execute(vo);
            map.put("total", actPage.getCount());
            map.put("rows", actPage.getPageObjects());
        }
        return map;
    }

    //数据权限机构
    @RequestMapping("user-right-org!data.action")
    @ResponseBody
    public Object dataUserRightOrg(HttpServletRequest request, String userId) {
        String parentId = request.getParameter("id");
        Org org = new Org();
        if (Validator.isNull(parentId)) {
            parentId = "0";
        }
        org.setFatherId(parentId);
        ParamsVo<Org> vo = new ParamsVo<Org>();
        vo.setObj(org);

        this.getSessionUser(request, vo);

        List<Org> list = orgManager.getList(vo);
        vo = new ParamsVo<Org>();
        vo.setInfoId(userId);
        vo.setKey("orgsByUserId");
        List<Org> giveList = (List<Org>) orgManager.execute(vo);

        net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
        if (Validator.isEmpty(list))
            return jary;
        for (int i = 0; i < list.size(); i++) {
            Org ovo = list.get(i);
            net.sf.json.JSONObject jvo = net.sf.json.JSONObject.fromObject(ovo);
            if (ovo.getSubCount() != null && ovo.getSubCount() > 0) {
                jvo.put("state", "closed");
            } else {
                jvo.put("state", "opened");
            }
            String hasGive = hasOrg(giveList, ovo.getOrgId()) ? "T" : "F";
            jvo.put("hasGive", hasGive);
            jary.add(jvo);
        }
        return jary;
    }

    //分配数据权限给用户
    @RequestMapping("user-data-give.action")
    @ResponseBody
    public ResultMsg userDataGive(HttpServletRequest request, String flag, String objId,
            String userId, String giveType) {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        ParamsVo<DataRight> vo = new ParamsVo<DataRight>();
        DataRight dataRight = new DataRight();
        dataRight.setUserId(userId);
        dataRight.setDataKey(objId);
        dataRight.setDataName(giveType);
        vo.setObj(dataRight);
        if ("add".equals(flag)) {
            dataRightManager.saveInfo(vo);
        } else {
            dataRightManager.deleteInfo(vo);
        }
        return rmsg;
    }

    //数据权限部门
    @RequestMapping("user-right-dept!data.action")
    @ResponseBody
    public Object dataUserRightDept(HttpServletRequest request, String userId) {
        String parentId = request.getParameter("id");
        if (Validator.isNull(parentId)) {
            parentId = "0";
        }
        ParamsVo<Dept> vo = new ParamsVo<Dept>();
        vo.setParams("fatherId", parentId);
        vo.setParams("userId", userId);
        vo.setParams("dataName", "dept");
        vo.setKey("ByFatherId");

        List<Dept> list = (List<Dept>) deptManager.execute(vo);
        vo.setParams("fatherId", null);
        List<Dept> giveList = (List<Dept>) deptManager.execute(vo);

        net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
        if (Validator.isEmpty(list))
            return jary;
        for (int i = 0; i < list.size(); i++) {
            Dept ovo = list.get(i);
            net.sf.json.JSONObject jvo = net.sf.json.JSONObject.fromObject(ovo);
            if (ovo.getSubCount() != null && ovo.getSubCount() > 0) {
                jvo.put("state", "closed");
            } else {
                jvo.put("state", "opened");
            }
            String hasGive = hasDept(giveList, ovo.getDeptId()) ? "T" : "F";
            jvo.put("hasGive", hasGive);
            jary.add(jvo);
        }
        return jary;
    }

    protected String getPrefix() {
        return "uct/user-";
    }

    private void getSessionUser(HttpServletRequest request, ParamsVo vo) {
        LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
        if (!Validator.isEmpty(loginUser)) {
            vo.setParams("userOrgId", loginUser.getOrgId());
            vo.setParams("sysUser", loginUser.getSysFlag());//是否为系统用户
        }
    }

    /**
     * 判断是否包含该权限值
     *
     * @param giveList 分配的权限值
     * @param actId 权限值id
     * @return boolean
     */
    private boolean hasGive(List<ActGive> giveList, String actId) {
        if (Validator.isEmpty(giveList))
            return false;
        for (int j = 0; j < giveList.size(); j++) {
            ActGive give = giveList.get(j);
            if (actId.equals(give.getActId())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否赋予机构数据级权限
     *
     * @param giveList
     * @param orgId
     * @return boolean
     */
    private boolean hasOrg(List<Org> giveList, String orgId) {
        if (Validator.isEmpty(giveList))
            return false;
        for (int j = 0; j < giveList.size(); j++) {
            Org vo = giveList.get(j);
            if (orgId.equals(vo.getOrgId())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否赋予部门数据级权限
     *
     * @param giveList
     * @return boolean
     */
    private boolean hasDept(List<Dept> giveList, String deptId) {
        for (int j = 0; j < giveList.size(); j++) {
            Dept vo = giveList.get(j);
            if (deptId.equals(vo.getDeptId())) {
                return true;
            }
        }
        return false;
    }
}
